package com.youlu.campus.service.rd.impl;

import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.req.ActivityJoinInfoRequest;
import com.youlu.campus.service.aomen.AoMenService;
import com.youlu.campus.service.rank.RankBaseService;
import com.youlu.campus.service.rank.RankService;
import com.youlu.campus.service.ranking.UniversityActivityRankingService;
import com.youlu.campus.service.ranking.UserActivityPointRankingProvinceService;
import com.youlu.campus.service.ranking.UserActivityPointRankingService;
import com.youlu.campus.service.ranking.entity.UserActivityPointProvinceRanking;
import com.youlu.campus.service.ranking.entity.UserActivityPointRanking;
import com.youlu.campus.service.rd.RdService;
import com.youlu.campus.service.visitor.VisitorUserService;
import com.youlu.campus.service.wechat.SystemNickNameAndHeaderImageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class RdServiceImpl implements RdService {
    @Autowired
    private RankService rankService;
    @Autowired
    private RankBaseService rankBaseService;
    @Autowired
    private UserActivityPointRankingService userActivityPointRankingService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private UserActivityPointRankingProvinceService userActivityPointRankingProvinceService;
    @Autowired
    private VisitorUserService visitorUserService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private UniversityActivityRankingService universityActivityRankingService;
    @Autowired
    private AoMenService aoMenService;

    @Override
    public boolean deleteSingleRank(String userId, String activityId) {
        log.info(":>>> 删除单独排行榜:{},{}", userId, activityId);
        String key = userActivityPointRankingService.getRankKey(activityId);
        rankBaseService.remove(key, userId);
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId).and("activityId").is(activityId));
        mongoTemplate.remove(query, UserActivityPointRanking.class);
        String province = visitorUserService.getUserProvince(activityId, userId);
        String pKey = userActivityPointRankingProvinceService.getRankKey(activityId, province);
        rankBaseService.remove(pKey, userId);
        mongoTemplate.remove(query, UserActivityPointProvinceRanking.class);
        mongoTemplate.remove(query, UserActivityPointDetail.class);
        mongoTemplate.remove(query, UserActivityTaskInfo.class);
        mongoTemplate.remove(query, UserActivityFootPrint.class);
        // 承办单位榜

        return true;
    }

    @Override
    public boolean deleteRank(String userId, String activityId) {
        log.info(":>>> 删除排行榜:{}", activityId);
        String key = userActivityPointRankingService.getRankKey(activityId);
        redisTemplate.delete(key);
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId));
        mongoTemplate.remove(query, UserActivityPointRanking.class);
        String[] provinces = rankService.getAllProvinces();
        for (int i = 0; i < provinces.length; i++) {
            String pKey = userActivityPointRankingProvinceService.getRankKey(activityId, provinces[i]);
            redisTemplate.delete(pKey);
        }
        mongoTemplate.remove(query, UserActivityPointProvinceRanking.class);
        mongoTemplate.remove(query, UserActivityPointProvinceRanking.class);
        mongoTemplate.remove(query, UniversityActivityTaskRanking.class);
        String universityKey = universityActivityRankingService.getUniversityRankKey(activityId);
        redisTemplate.delete(universityKey);
        return true;
    }

    @Override
    public void syncJoinInfo(ActivityJoinInfoRequest request) {
        if (StringUtils.isBlank(request.getActivityId())) {
            return;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(request.getActivityId()));
        query.addCriteria(Criteria.where("joined").is(true));
        if (request.getStartTime() != null && request.getEndTime() != null) {
            query.addCriteria(Criteria.where("signUpTime").lte(request.getEndTime()).gte(request.getStartTime()));
        }
        query.addCriteria(Criteria.where("otherPlatformOpenId").is(null));
        long count  = mongoTemplate.count(query,UserParticipateActivityInfo.class);
        log.info("count:{}",count);
        if (request.getSyncNum() != null) {
            query.limit(request.getSyncNum());
        }
        List<UserParticipateActivityInfo> joinList = mongoTemplate.find(query, UserParticipateActivityInfo.class);
        if(request.getShowDataList()){
            log.info("list:{}",joinList);
        }
        if(request.getSyncData()){
            joinList.forEach(item->{
                if(StringUtils.isNotBlank(item.getMobile())){
                    aoMenService.doPushUserPhone(item.getMobile(),request.getActivityId(),item.getUserId());
                }
            });
        }
    }

    @Autowired
    private SystemNickNameAndHeaderImageService systemNickNameAndHeaderImageService;

    @Override
    public void updateWechatGrayLogo() {
        List<WechatMiniUserPO> list = mongoTemplate.find(new Query(Criteria.where("nickName").is("微信用户")),WechatMiniUserPO.class);
        if(CollectionUtils.isNotEmpty(list)){
            list.forEach(item->{
                SystemNickNameAndHeaderImage image = systemNickNameAndHeaderImageService.getRandom();
                item.setNickName(image.getNickName());
                item.setAvatarUrl(image.getAvatarUrl());
                mongoTemplate.save(item);
            });
        }
    }
}
